﻿Imports SQLUtil.SQL
Imports HTSQLiteManager
Imports System.IO
Imports System.Net

Public Class frmUpdate
    Public oColumns As New Collection()    

    Private Sub butCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butCancel.Click            
        Me.Close()
    End Sub

    Private Sub frmUpdate_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load        
        ' set MaxLength cho cac Textbox tuong ung voi cac truong trong database
        'Try            
        '    Dim strSQL As String
        '    strSQL = "SELECT name, prec AS Maxlength FROM syscolumns "
        '    strSQL += "WHERE (id IN (SELECT id FROM sysobjects WHERE name = '" + clsDefine.cTable + "'))"
        '    Dim dsColumns As New DataSet
        '    Dim iColumn As Integer
        '    SQLRetrieve(frmMain.appConn, strSQL, "syscolumns", dsColumns)
        '    With dsColumns.Tables("syscolumns")
        '        For iColumn = 0 To .Rows.Count - 1
        '            oColumns.Add(.Rows(iColumn).Item("Maxlength"), Trim(.Rows(iColumn).Item("Name")))
        '        Next
        '    End With
        '    Dim iControl As Control
        '    For Each iControl In Me.Controls
        '        If Microsoft.VisualBasic.Left(iControl.Tag, 1) = "F" Then
        '            If iControl.GetType().Name = "RichTextBox" Then
        '                Dim iText As RichTextBox
        '                iText = iControl
        '                Dim cFieldName = Microsoft.VisualBasic.Right(iControl.Name, iControl.Name.Length - 3)
        '                If Mid(iControl.Tag, 2, 1) = "C" Then
        '                    ' Set MaxLength
        '                    iText = iControl
        '                    iText.MaxLength = oColumns(cFieldName)
        '                End If
        '            ElseIf iControl.GetType().Name = "Label" Then
        '                Continue For
        '            Else
        '                Dim iText As TextBox
        '                iText = iControl
        '                Dim cFieldName = Microsoft.VisualBasic.Right(iControl.Name, iControl.Name.Length - 3)
        '                If Mid(iControl.Tag, 2, 1) = "C" Then
        '                    ' Set MaxLength
        '                    iText = iControl
        '                    iText.MaxLength = oColumns(cFieldName)
        '                End If
        '            End If
        '        End If
        '    Next
        '    dsColumns = Nothing

        '    'add valid            
        'Catch ex As Exception
        'End Try

    End Sub

    Public Sub txtKeyPressEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If AscW(e.KeyChar) = 13 Then
            SendKeys.Send("{Tab}")
        End If
    End Sub
    Public Sub txtNumericKeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles txtVol.KeyPress, txtNum_of_song.KeyPress
        Dim tb As TextBox = CType(sender, TextBox)
        Dim chr As Char = e.KeyChar
        If IsNumeric(e.KeyChar) And Not e.KeyChar = "-" Then
            e.Handled = Not IsNumeric(tb.Text & e.KeyChar)
        ElseIf e.KeyChar = "." Then
            If Not (tb.SelectedText = "." Or IsNumeric(tb.Text & e.KeyChar)) Then
                e.Handled = True
            End If
        ElseIf e.KeyChar = "-" Then
            If tb.SelectionStart <> 0 Or Microsoft.VisualBasic.Left(tb.Text, 1) = "-" Then
                e.Handled = True
            End If
        ElseIf Not Char.IsControl(e.KeyChar) Then
            e.Handled = True
        End If
    End Sub

    Private Sub butOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butOk.Click
        butOk.Enabled = False
        Dim t As New Threading.Thread(AddressOf PackageStart)
        t.Start()
    End Sub
    Private Sub PackageStart()
        'Get songs by vol
        Dim strSQL As String
        Dim colSelect As String = "[code],[title],[title_unmark],[title_short],[lyrics],[lyrics_unmark],[lyrics_short],[writer_name],[writer_unmark],[writer_short],[singer_name],[singer_unmark],[singer_short],[genre_name],[genre_unmark],[genre_short],[vol],[url],[rate],[like_nd],[status]"
        strSQL = "SELECT " + colSelect + " FROM tbl_songs where vol = '" + Trim(txtVol.Text) + "' "
        Dim dsSongs As New DataSet
        SQLRetrieve(frmMain.appConn, strSQL, "tbl_songs", dsSongs)
        Dim tableSong As DataTable = dsSongs.Tables("tbl_songs")

        If tableSong.Rows.Count = 0 Then Return

        Dim currentPath As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\klist.db"
        Dim fileName As String = Trim(txtVol.Text) + ".db"
        'txtFile_path.Text = fileName
        Dim folderPath As String = Environment.ExpandEnvironmentVariables("%AppData%\" + "TriViet\")
        Dim path As String = folderPath + fileName
        If Not System.IO.Directory.Exists(folderPath) Then
            System.IO.Directory.CreateDirectory(folderPath)
        End If

        File.Copy(currentPath, path, True)

        'insert data to sqllite
        Dim sqlite As IHTSQLManager = HTSQLManager.GetInstance()
        If sqlite.ConnectDatabase(path) Then
            Dim Sql As String = String.Empty
            Dim rs As Boolean = False
            Dim rows As Integer = tableSong.Rows.Count
            Dim i As Integer
            For i = 0 To rows - 1
                Dim row = tableSong.Rows(i)
                Sql = "INSERT INTO tbl_songs VALUES('"
                Sql += Trim(row.Item(0)) + "','"
                Sql += Trim(row.Item(1)) + "','"
                Sql += Trim(row.Item(2)) + "','"
                Sql += Trim(row.Item(3)) + "','"
                Sql += Trim(row.Item(4)) + "','"
                Sql += Trim(row.Item(5)) + "','"
                Sql += Trim(row.Item(6)) + "','"
                Sql += Trim(row.Item(7)) + "','"
                Sql += Trim(row.Item(8)) + "','"
                Sql += Trim(row.Item(9)) + "','"
                Sql += Trim(row.Item(10)) + "','"
                Sql += Trim(row.Item(11)) + "','"
                Sql += Trim(row.Item(12)) + "','"
                Sql += Trim(row.Item(13)) + "','"
                Sql += Trim(row.Item(14)) + "','"
                Sql += Trim(row.Item(15)) + "','"
                Sql += Trim(row.Item(16)) + "','"
                Sql += Trim(row.Item(17)) + "','"
                Sql += Trim(row.Item(18)) + "','"
                Sql += Trim(row.Item(19)) + "','"
                Sql += Trim(row.Item(20)) + "','"
                Sql += Date.Now + "')"
                rs = sqlite.ExecuteSQL(Sql)
                Dim arr() As Integer = {i, rows}
                proBar.Invoke(New Action(Of Integer())(AddressOf ProgressInsertSQLLite), arr)
            Next i
            sqlite.CloseDatabase()

            proBar.Invoke(New MethodInvoker(AddressOf ReSetProBar))

            'insert data to tbl_vol_update
            'Dim tableInsert As New DataTable
            'tableInsert.Columns.Add("vol", GetType(String))
            'tableInsert.Columns.Add("file_path", GetType(String))
            'tableInsert.Columns.Add("crypt_key", GetType(String))
            'tableInsert.Columns.Add("file_size", GetType(Long))
            'tableInsert.Columns.Add("create_date", GetType(DateTime))
            'tableInsert.Columns.Add("last_update_date", GetType(DateTime))
            'tableInsert.Columns.Add("approved", GetType(String))

            'Dim fileLength As Long = My.Computer.FileSystem.GetFileInfo(path).Length
            'tableInsert.Rows.Add(txtVol.Text, fileName, Nothing, fileLength, DateTime.Now, DateTime.Now, "1")


            'strSQL = "SELECT * FROM tbl_vol_update where vol = '" + txtVol.Text + "' "
            'Dim dsRow As New DataSet
            'SQLRetrieve(frmMain.appConn, strSQL, "tbl_vol_update", dsRow)

            'If dsRow.Tables("tbl_vol_update").Rows.Count = 0 Then
            '    SQLInsert(frmMain.appConn, "tbl_vol_update", tableInsert.Rows(0))
            'End If

            'If dsRow.Tables("tbl_vol_update").Rows.Count > 0 Then
            '    Dim sqlUpdate As String = "UPDATE tbl_vol_update SET file_size = " + fileLength.ToString() + ",last_update_date='" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "' WHERE vol=" + txtVol.Text
            '    SQLExecute(frmMain.appConn, sqlUpdate)
            'End If

            'upload file to server
            'Delegate upload here
            Me.Invoke(New Action(Of String)(AddressOf StartUpload), path)

        End If
    End Sub

    Private Sub StartUpload(ByVal path As String)
        Dim uploadUrl As String = "http://xhuutrix.no-ip.org:8080/tvarirang/upload-gate"
        Dim userName As String = "TV-ARRIRANG"
        Dim password As String = "TV2013-ARRIRANG"


        'Start the upload.
        Dim client As New WebClient

        'Attach the event handlers to the new WebClient
        Try
            AddHandler client.UploadProgressChanged, AddressOf UploadProgressChanged
            AddHandler client.UploadFileCompleted, AddressOf UploadFileCompleted

            client.UploadFileAsync(New Uri(uploadUrl), path)
        Catch ex As Exception
            MessageBox.Show("Error upload: " + ex.Message)
        End Try
    End Sub
    Private Sub ReSetProBar()
        Me.proBar.Text = "Upload progress:"
        Me.proBar.Value = 0
        Me.proBar.Visible = True
    End Sub

    Private Sub ReSetbtnPackate()
        butOk.Enabled = True
    End Sub

    Private Sub ProgressInsertSQLLite(ByVal arr As Integer())
        proBar.Value = CStr(arr(0) / arr(1) * proBar.Maximum)
    End Sub


    Private Sub UploadProgressChanged(ByVal sender As Object, ByVal e As System.Net.UploadProgressChangedEventArgs)        
        proBar.Invoke(New Action(Of Integer)(AddressOf InvokeProcessValue), e.ProgressPercentage)
    End Sub

    Private Sub UploadFileCompleted(ByVal sender As Object, ByVal e As System.Net.UploadFileCompletedEventArgs)
        Dim client As WebClient = DirectCast(sender, WebClient)
        Dim response As String = System.Text.Encoding.UTF8.GetString(e.Result)
        'Remove the event handlers
        RemoveHandler client.UploadProgressChanged, AddressOf UploadProgressChanged
        RemoveHandler client.UploadFileCompleted, AddressOf UploadFileCompleted
        butOk.Invoke(New MethodInvoker(AddressOf ReSetbtnPackate))

        Me.NotifyUploadComplete()
    End Sub
    
    Private Delegate Sub NotifyUploadCompleteHandler()

    Private Sub NotifyUploadComplete()
        If Me.InvokeRequired Then
            Me.Invoke(New NotifyUploadCompleteHandler(AddressOf NotifyUploadComplete))
        Else
            Me.proBar.Visible = False
            MessageBox.Show("Upload complete")
        End If
    End Sub

    Private Sub InvokeProcessValue(ByVal progressPercentage As Integer)
        If (progressPercentage >= proBar.Maximum) Or (progressPercentage < proBar.Minimum) Then progressPercentage = proBar.Maximum
        proBar.Value = CStr(progressPercentage)
    End Sub
End Class